package ucadminlogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/usercenter"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateAppConfigLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateAppConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateAppConfigLogic {
	return &UpdateAppConfigLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 更新app配置
func (l *UpdateAppConfigLogic) UpdateAppConfig(in *pb.UpdateAppConfigReq) (*pb.UpdateAppConfigResp, error) {
	defer utils.RecoverPanic()

	var ac *usercenter.AppConfig
	var err error
	ac, err = l.svcCtx.AppConfigModel.FindOne(l.ctx, in.AppVersion)
	if err != nil && err != usercenter.ErrNotFound {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	if ac == nil {
		ac = &usercenter.AppConfig{
			AppVersion: in.AppVersion,
			CheckState: in.CheckState,
			TextState:  in.TextState,
			PayState:   in.PayState,
			RankState:  in.RankState,
			Name:       in.Name,
			PkgName:    in.PkgName,
			Remark:     in.Remark,
		}
		_, err = l.svcCtx.AppConfigModel.Insert(l.ctx, ac)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
		return &pb.UpdateAppConfigResp{}, nil
	}
	if in.CheckState != 0 {
		ac.CheckState = in.CheckState
	}
	if in.TextState != 0 {
		ac.TextState = in.TextState
	}
	if in.PayState != 0 {
		ac.PayState = in.PayState
	}
	if in.RankState != 0 {
		ac.RankState = in.RankState
	}
	if in.Name != "" {
		ac.Name = in.Name
	}
	if in.PkgName != "" {
		ac.PkgName = in.PkgName
	}
	if in.Remark != "" {
		ac.Remark = in.Remark
	}
	err = l.svcCtx.AppConfigModel.Update(l.ctx, ac)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	return &pb.UpdateAppConfigResp{}, nil
}
